# -*- coding: utf-8 -*-

# Copyright (C) 2010 David Byers <david.byers@liu.se>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
from PyKDE4.kdeui import *
from PyKDE4.kdecore import *

from status import StatusDialog
from configuration import MPDConfig

from qmpd import QMPD
from buttons import ActionButton, PlayButton, StopButton, NextButton, PrevButton, VolumeSlider, StatusButton

class MPDController(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)
        self.client = QMPD()

    def init(self):
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.theme = Plasma.Svg(self)
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
        self.layout.setContentsMargins(0,2,0,0)
        self.layout.setSpacing(1)

        self.settings = {}
        gc = self.config()

        self.settings["server"] = self.readEntry(gc, "server", "");
        self.settings["port"] = int(self.readEntry(gc, "port", "6600"));
        self.settings["password"] = self.readEntry(gc, "password", "");

        self.resize(300,24)
        self.applet.setLayout(self.layout)

        self.playButton = PlayButton(self.applet, self.client)
        self.nextButton = NextButton(self.applet, self.client)
        self.prevButton = PrevButton(self.applet, self.client)
        self.stopButton = StopButton(self.applet, self.client)
        self.volume = VolumeSlider(self.applet, self.client)
        self.statusButton = StatusButton(self, self.client)

        self.layout.addItem(self.statusButton)
        self.layout.addItem(self.prevButton)
        self.layout.addItem(self.stopButton)
        self.layout.addItem(self.playButton)
        self.layout.addItem(self.nextButton)
        self.layout.addItem(self.volume)

        self.dialog = StatusDialog(self.client)
        self.dialogTimer = QTimer()
        self.dialogTimer.setSingleShot(True)
        self.connect(self.dialogTimer, SIGNAL("timeout()"), self.show_status)

        self.mpd_connect()

    def hoverEnterEvent(self, event):
        self.dialogTimer.start(1000)

    def hoverLeaveEvent(self, event):
        self.dialogTimer.stop()
        self.hide_status()

    def mpd_connect(self):
        if self.settings["server"] and self.settings["port"]:
            self.client.mpd_connect(self.settings["server"],
                    self.settings["port"], self.settings["password"])
        #else:
        #    self.set_error("No server configured", "Open the playback controller settings")

    def show_status(self):
        if self.configurationRequired():
            self.showConfigurationInterface()
        else:
            self.dialog.setMinimumWidth(self.size().width())
            self.dialog.move(self.popupPosition(self.dialog.sizeHint()))
            self.dialog.show()

    def hide_status(self):
        if not self.dialog.persistent:
            self.dialog.hide()

    def toggle_status(self):
        if self.dialog.isVisible():
            if self.dialog.is_extended():
                self.dialog.hide()
                #self.hide_status()
                self.dialog.persistent = False
                self.dialog.set_extended(False)
                self.dialog.move(self.popupPosition(self.dialog.sizeHint()))
                self.dialog.show()
                #self.show_status()
            else:
                self.dialog.hide()
                #self.hide_status()
                self.dialog.persistent = True
                self.dialog.set_extended(True)
                self.dialog.move(self.popupPosition(self.dialog.sizeHint()))
                self.dialog.show()
                #self.show_status()
        else:
            self.dialog.persistent = True
            self.dialog.set_extended(True)
            self.show_status()

    def configurationRequired(self):
        return not self.settings["server"] or not self.settings["port"]

    def createConfigurationInterface(self, parent):
        self.mpd_config = MPDConfig(self, self.settings)
        p = parent.addPage(self.mpd_config, "MPD Server")
        p.setIcon(KIcon("preferences-desktop-multimedia"))

        self.connect(parent, SIGNAL("okClicked()"), self.configAccepted)
        self.connect(parent, SIGNAL("cancelClicked()"), self.configDenied)

    def configAccepted(self):
        self.settings = self.mpd_config.exportSettings()
        gc = self.config()

        gc.writeEntry("server", self.settings["server"])
        gc.writeEntry("port", str(self.settings["port"]))

        self.mpd_connect()

    def configDenied(self):
        self.mpd_config.deleteLater()

    def readEntry(self, gc, key, default):
        val = gc.readEntry(key, default)
        if type(val) == QVariant:
            return str(val.toString())
        else:
            return val
 
def CreateApplet(parent):
    return MPDController(parent)
